public class gas {
    private static int updateWithinRange (int index, int len) {
        if (index > len) {
            return index - len;
        } else if (index < 0) {
            return index + len;
        } else {
            return index;
        }
    }
    
    public static int canCompleteCircuit(int[] gas, int[] cost) {
        // Note: The Solution object is instantiated only once and is reused by each test case.
        int len = gas.length, forward_index = 0, backward_index = len - 1, cur_sum = 0;
        
        if (len == 0) {
            return 0;
        } else if (len == 1) {
            if (gas[0] >= cost[0]) {
                return 0;
            } else {
                return -1;
            }
        }
        
        // DEBUG
        System.out.println("Forward index is " + forward_index);
        System.out.println("Backward index is " + backward_index);
            
        // calculate the gas - cost difference
        while (forward_index != backward_index) {
            if (cur_sum >= 0) {
                cur_sum += gas[forward_index] - cost[forward_index];
                forward_index++;
            } else {
                cur_sum += gas[backward_index] - cost[backward_index];
                backward_index--;
            }
            // DEBUG
            System.out.println("Forward index is " + forward_index);
            System.out.println("Backward index is " + backward_index);
            System.out.println("Current sum is " + cur_sum);
        }
        
        // update with the last one
        cur_sum += gas[forward_index] - cost[forward_index];
        // DEBUG
        System.out.println("Current sum is " + cur_sum);
        if (cur_sum >= 0) {
            return forward_index; 
        } else {
            return -1;
        } 
    }
    
    public static void main(String[] args) {
      int[] gas = {2,4};
      int[] cost = {3,4};
      System.out.println(canCompleteCircuit(gas, cost));
    }
}